<template>
  <div class="appointment-container">
    <h1>立即预约</h1>
    <el-form :model="appointmentForm" :rules="rules" ref="formRef" label-position="right" label-width="100px">
      <el-form-item label="患者 ID" prop="patientId">
        <!-- 设置输入框为禁用状态 -->
        <el-input v-model.number="appointmentForm.patientId" autocomplete="off" placeholder="请输入患者 ID" disabled></el-input>
      </el-form-item>
      <el-form-item label="预约日期" prop="date">
        <el-date-picker
            v-model="appointmentForm.date"
            type="date"
            placeholder="选择预约日期"
            value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitAppointment">提交预约</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters(['getUserId']) // 假设 Vuex 中存储的是
  },
  data() {
    return {
      appointmentForm: {
        patientId: null,
        escortId: null,
        date: null
      },
      rules: {
        patientId: [
          { required: true, message: '请等待患者 ID 加载', trigger: 'blur' },
          { type: 'number', message: '患者 ID 必须为数字值', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请选择预约日期', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    // 在组件创建时获取患者 ID
    this.getPatientId();
  },
  methods: {
    async getPatientId() {
      const UserId = this.getUserId;
      try {
        const res = await axios.get(`/api/wu_vue_2_test/Patient/getByUserId?UserId=${UserId}`);
        if (res.data.code === 200) {
          this.appointmentForm.patientId = res.data.data.patientId;
        } else {
          ElMessage.error(res.data.message);
        }
      } catch (error) {
        console.error('获取患者 ID 失败:', error);
        ElMessage.error('获取患者 ID 失败，请稍后重试');
      }
    },
    async submitAppointment() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.post('/api/wu_vue_2_test/Appointment/add', this.appointmentForm);
            if (res.data.code === 200) {
              ElMessage.success('预约成功');
              this.appointmentForm = {
                patientId: this.appointmentForm.patientId, // 保留患者 ID
                escortId: null,
                date: null
              };
            } else {
              ElMessage.error(res.data.message);
            }
          } catch (error) {
            console.error('预约失败:', error);
            ElMessage.error('预约失败，请稍后重试');
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.appointment-container {
  padding: 20px;
}
</style>